<?php

namespace Modules\Order\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Order\Entities\ExportOrder as Order;
use Modules\Order\Exports\OrderExport;

use Auth;
use Validator;
use ThrowException;

use Cache;

class OrderExportController extends Controller
{
    public function total(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $options = $req->all();

        $total = Order::getBuilder($options)->count();

        return [
            'total' => $total
        ];
    }

    public function store(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();


        $uuid = str_random(30);

        $cached = $req->all();

        Cache::put($uuid, $cached, 10);

        return [
        	'url' => '/admin-api/export/orders/' . $uuid,

        ]; 
    }

    public function show(Request $req, $uuid)
    {
    	$rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $cached = Cache::get($uuid) ?: ThrowException::Conflict('未找到缓存内容');

        $cached['per_page'] = 1000000;
        $cached['where'][] = ['user_id', '>', 500];

        $orders = Order::getList($cached)->list;

        $file = '订单导出.xlsx';
        return (new OrderExport($orders))->download($file); 
    }
}
